package firear.tvutils.ws.serv.req;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;

import firear.tvutils.ws.Constants;
import firear.tvutils.ws.WSApplication;
import firear.tvutils.ws.serv.support.HttpGetParser;
import firear.tvutils.ws.serv.support.Progress;
import firear.tvutils.ws.util.CallMedlaPlayer;

public class HttpParseUrlHandler implements HttpRequestHandler {
    private final String TAG = "HttpParseUrlHandler";
    private WebView mWebView = null;
    private String mLastUrl = "";
    private long mLasttime = 0;
    private Handler mHandler = null;
    private MyThread2 mDealThread = null;

    public synchronized void releaseWebViews() {
        if(mWebView != null) {
            try {
                if(mWebView.getParent() != null) {
                    ((ViewGroup) mWebView.getParent()).removeView(mWebView);
                }
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
//this is causing the segfault occasionally below 4.2
                mWebView.destroy();
                //                }
            }catch (IllegalArgumentException e) {

            }

            mWebView = null;
        }
    }

    class MyThread2 extends Thread {
        @Override
        public void run() {
            super.run();
            Looper.prepare();

            mHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    Log.i(TAG, "handle msg");
                    test((String)msg.obj);

                    super.handleMessage(msg);

                }
            };
            Looper.loop();
            Log.i(TAG, "Thread X");
        }
    }


    public HttpParseUrlHandler(){
        super();
        if(mDealThread == null){
            mDealThread = new MyThread2();
            mDealThread.start();
        }
    }

    @Override
    public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {

        HttpGetParser parser = new HttpGetParser();
        Map<String, String> params = parser.parse(httpRequest);
        String url = params.get("url");
        url = URLDecoder.decode(url, Constants.Config.ENCODING);
        Log.e("tt", "get play url = " + url);
        if(mLastUrl != url || System.currentTimeMillis() - mLasttime > 10000000) {

            if(mHandler != null){
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = url;
                mHandler.sendMessage(msg);
                Log.e("tt", "send msg = " + url);
                mLasttime = System.currentTimeMillis();
                mLastUrl = url;
            }else {
                Log.i(TAG, "hand null");
            }
        }else {
            Log.i("tt", "ignore:" + url);
        }

        HttpEntity entity = null;
        String contentType = "text/html;charset=" + Constants.Config.ENCODING;

        httpResponse.setStatusCode(HttpStatus.SC_OK);
        Progress.clear();
    }

    public final class InJavaScriptLocalObj
    {
        @JavascriptInterface
        public void showSource(String html) {
            Log.i(TAG, "====>src html=" + html);
        }

        @JavascriptInterface
        public void showDescription(String str) {
            Log.i(TAG, "====>deschtml=" + str);
        }
    }

    @SuppressLint("JavascriptInterface")
    public synchronized void test(String url) {
        releaseWebViews();
        Context ct = WSApplication.getInstance().getApplicationContext();

        Log.i(TAG, "HttpParseUrlHandler E");
        Log.i(TAG, "ct=" + ct);
        mWebView = new WebView(ct);
        // 开启JavaScript支持
        mWebView.getSettings().setJavaScriptEnabled(true);

        //mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");

        // 设置WebView是否支持使用屏幕控件或手势进行缩放，默认是true，支持缩放
        //mWebView.getSettings().setSupportZoom(true);

        // 设置WebView是否使用其内置的变焦机制，该机制集合屏幕缩放控件使用，默认是false，不使用内置变焦机制。
        //mWebView.getSettings().setBuiltInZoomControls(true);

        // 设置是否开启DOM存储API权限，默认false，未开启，设置为true，WebView能够使用DOM storage API
        //mWebView.getSettings().setDomStorageEnabled(true);

        // 触摸焦点起作用.如果不设置，则在点击网页文本输入框时，不能弹出软键盘及不响应其他的一些事件。
        //mWebView.requestFocus();

        // 设置此属性,可任意比例缩放,设置webview推荐使用的窗口
        //mWebView.getSettings().setUseWideViewPort(true);

        // 设置webview加载的页面的模式,缩放至屏幕的大小
        //mWebView.getSettings().setLoadWithOverviewMode(true);

        // 加载链接
        mWebView.loadUrl(url);

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // 在开始加载网页时会回调
                Log.i(TAG, "onPageStarted " + url);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 拦截 url 跳转,在里边添加点击链接跳转或者操作
                //view.loadUrl(url);
                Log.i(TAG, "shouldOverrideUrlLoading " + url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // 在结束加载网页时会回调

                Log.i(TAG, "onPageFinished " + url);
                // 获取页面内容
                //view.loadUrl("javascript:window.java_obj.showSource(document.getElementsByTagName('html')[0].innerHTML);");

                // 获取解析<meta name="share-description" content="获取到的值">
                //view.loadUrl("javascript:window.java_obj.showDescription(document.querySelector('meta[name=\"share-description\"]').getAttribute('content'));");
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String request) {
                // 在每一次请求资源时，都会通过这个函数来回调
                int index = request.indexOf('?');
                String uri = index == -1 ? request : request.substring(0, index);
                uri.toLowerCase();

                if (uri.endsWith("m3u8")){
                    Log.i(TAG, "shouldInterceptRequest " + request);
                    CallMedlaPlayer.callMxPlayer(request, WSApplication.getInstance().getApplicationContext());
                }

                if (request.endsWith(".png") || request.endsWith(".ico") || request.endsWith(".gif")) {
                    return null;
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            }
        });
    }
}
